#!/bin/bash
#$BASE_PROJECT 指的是新Project的基础Project
#$NEW_PROJECT 指的是将创建的新的Project
#$PLATFORM 指的是平台信息，如MT6797等
#$COMPANY 指的是开案公司的名字，如lenovo, tinno, huawei等等。
#$ARM_TYPE 指的是芯片的位数

#===================格式化输出====================#
SCRIPT=$(basename $0)
SCRIPT=${SCRIPT%.*}
SCRIPT_VERSION=v1.0.3
#echo ${SCRIPT}
#echo ${SCRIPT_VERSION}
#exit 1
SERVER="192.168.2.60"
USER="autoftp"
PASSWD="teksun2016"

RED="\033[0;31m"
YELLOW="\033[1;33m"
GREEN="\033[4;32m"
NO_COLOR="\033[0m"
BOLD="\033[1m"
UNDERLINE="\033[4m"
warn_debug=true
DEBUG=false

if [ "${DEBUG}" == "true" ];then
	CP="$(which cp) -v"
else
	CP="$(which cp)"
fi

printHelp(){
printf "Help:
\t$(basename $0) --clone old_project new_project\t\t克隆驱动基础文件夹
\t$(basename $0) --rename old_project new_project\t\t重命名项目
\t$(basename $0) --cloneall old_project new_project\t克隆全部文件

EXAMPLE: 
\t$(basename $0) --clone h898bc_v2_i_kb_exp h898bc_v2_i_kb_test

版本号:${SCRIPT_VERSION}
"
exit 1
}

die() {
	echo -e "==> ${RED}${@}${NO_COLOR}"
	exit 1
}

warn() {
	if [[ "$warn_debug" = true ]]; then
		echo -e "==> ${YELLOW}${@}${NO_COLOR}"
	fi
}

good() {
	echo -e "==> ${GREEN}${*}${NO_COLOR}"
}

#===================自定义函数====================#
getConfigValue(){
	local key=$1
	grep -v "^\s*#"  ${BASE_PROJECT}/device/*/*/ProjectConfig.mk | grep -w ${key} | tail -1 | sed 's#^[^=]*=\(.*\)$#\1#g' | sed 's#[[:space:]]##g'

}

#ftp连接
function FTP(){
echo " open ${SERVER}
user ${USER} ${PASSWD}
$@
bye
" | ftp -n 
}

forceUpdate(){
	good "当前版本:${SCRIPT_VERSION}"
	local server_backup="/scripts_tools"
	local server_size=$(FTP "ls ${server_backup}/${SCRIPT}" | awk -F" " '{print$5}')
	#good ${server_size}
	local local_size=$(ls -l `which ${SCRIPT}` | awk -F" " '{print$5}')
	#good ${local_size}
	if [ "${local_size}" != "${server_size}" ];then
		good "${SCRIPT}版本有更新"
		git-gerrit update 
		local new_version=$(${SCRIPT} | grep 版本号 | awk -F":" '{print$2}')
		good "最新版本:${new_version}"
		exit 0
	fi
}
checkExecPath(){
	local curdir=$(readlink -f .)
	#good "当前路径:$curdir"
	if [ "$(basename ${curdir})" != "teksun" ];then
		die "${SCRIPT}脚本只允许在teksun目录使用!"
	fi
}

#clone preloader
clonePreloader(){
	cd vendor/mediatek/proprietary/bootable/bootloader/preloader/custom/
	warn "$(pwd)"
	if [ "${action}" == "clone" ];then
		${CP} -r ${BASE_PROJECT} ${NEW_PROJECT}
	elif [ "${action}" == "rename" ];then
		mv ${BASE_PROJECT} ${NEW_PROJECT}
	fi

	mv ${NEW_PROJECT}/${BASE_PROJECT}.mk ${NEW_PROJECT}/${NEW_PROJECT}.mk
	sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g ${NEW_PROJECT}/${NEW_PROJECT}.mk
	good "${action} preloader\t\tDone"
	cd - >/dev/null
}
#clone lk
cloneLk(){
	cd vendor/mediatek/proprietary/bootable/bootloader/lk/ 
	warn "$(pwd)"
	if [ "${action}" == "clone" ];then
		${CP} project/${BASE_PROJECT}.mk project/${NEW_PROJECT}.mk
		${CP} -r target/${BASE_PROJECT} target/${NEW_PROJECT}
	elif [ "${action}" == "rename" ];then
		mv project/${BASE_PROJECT}.mk project/${NEW_PROJECT}.mk
		mv target/${BASE_PROJECT} target/${NEW_PROJECT}
	fi

	sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g project/${NEW_PROJECT}.mk
	good "${action} lk\t\t\tDone"
	cd - >/dev/null
}
#clone kernel
cloneKernel(){
	cd ${KERNEL}
	warn "$(pwd)"
	if [ "${action}" == "clone" ];then
		test -d drivers/misc/mediatek/mach/${PLATFORM}/${BASE_PROJECT} && ${CP} -r drivers/misc/mediatek/mach/${PLATFORM}/${BASE_PROJECT} drivers/misc/mediatek/mach/${PLATFORM}/${NEW_PROJECT} 
		test -f arch/${ARM_TYPE}/boot/dts/${BASE_PROJECT}.dts && ${CP} arch/${ARM_TYPE}/boot/dts/${BASE_PROJECT}.dts arch/${ARM_TYPE}/boot/dts/${NEW_PROJECT}.dts
		#针对mediatek最新代码,移动了dts文件的位置
		test -f drivers/misc/mediatek/dws/${PLATFORM}/${BASE_PROJECT}.dws && ${CP} -r drivers/misc/mediatek/dws/${PLATFORM}/${BASE_PROJECT}.dws drivers/misc/mediatek/dws/${PLATFORM}/${NEW_PROJECT}.dws 
		test -f arch/${ARM_TYPE}/boot/dts/mediatek/${BASE_PROJECT}.dts && ${CP} arch/${ARM_TYPE}/boot/dts/mediatek/${BASE_PROJECT}.dts arch/${ARM_TYPE}/boot/dts/mediatek/${NEW_PROJECT}.dts
		#${CP} arch/${ARM_TYPE}/configs/${BASE_PROJECT}_defconfig arch/${ARM_TYPE}/configs/${NEW_PROJECT}_defconfig
		#${CP} arch/${ARM_TYPE}/configs/${BASE_PROJECT}_debug_defconfig  arch/${ARM_TYPE}/configs/${NEW_PROJECT}_debug_defconfig
	elif [ "${action}" == "rename" ];then
		test -d drivers/misc/mediatek/mach/${PLATFORM}/${BASE_PROJECT} && mv drivers/misc/mediatek/mach/${PLATFORM}/${BASE_PROJECT} drivers/misc/mediatek/mach/${PLATFORM}/${NEW_PROJECT} 
		test -f arch/${ARM_TYPE}/boot/dts/${BASE_PROJECT}.dts && mv arch/${ARM_TYPE}/boot/dts/${BASE_PROJECT}.dts arch/${ARM_TYPE}/boot/dts/${NEW_PROJECT}.dts
		#兼容mediatek最新的文件存放位置
		test -f drivers/misc/mediatek/dws/${PLATFORM}/${BASE_PROJECT}.dws && mv drivers/misc/mediatek/dws/${PLATFORM}/${BASE_PROJECT}.dws drivers/misc/mediatek/dws/${PLATFORM}/${NEW_PROJECT}.dws
		test -f arch/${ARM_TYPE}/boot/dts/mediatek/${BASE_PROJECT}.dts && mv arch/${ARM_TYPE}/boot/dts/mediatek/${BASE_PROJECT}.dts arch/${ARM_TYPE}/boot/dts/mediatek/${NEW_PROJECT}.dts
		#kernel config 被转移到device下面
		#mv arch/${ARM_TYPE}/configs/${BASE_PROJECT}_defconfig arch/${ARM_TYPE}/configs/${NEW_PROJECT}_defconfig
		#mv arch/${ARM_TYPE}/configs/${BASE_PROJECT}_debug_defconfig  arch/${ARM_TYPE}/configs/${NEW_PROJECT}_debug_defconfig
	fi
	#sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g arch/${ARM_TYPE}/configs/${NEW_PROJECT}_defconfig
	#sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g arch/${ARM_TYPE}/configs/${NEW_PROJECT}_debug_defconfig
	good "${action} ${KERNEL}\t\tDone"
	cd - >/dev/null
}
#clone android
cloneAndroid(){
	warn "$(pwd)"
	if [ "${action}" == "clone" ];then
		${CP} -r device/${COMPANY}/${BASE_PROJECT} device/${COMPANY}/${NEW_PROJECT}
		mv device/${COMPANY}/${NEW_PROJECT}/full_${BASE_PROJECT}.mk device/${COMPANY}/${NEW_PROJECT}/full_${NEW_PROJECT}.mk
		${CP} -r vendor/mediatek/proprietary/custom/${BASE_PROJECT} vendor/mediatek/proprietary/custom/${NEW_PROJECT}
		${CP} vendor/mediatek/proprietary/trustzone/custom/build/project/${BASE_PROJECT}.mk vendor/mediatek/proprietary/trustzone/custom/build/project/${NEW_PROJECT}.mk
		${CP} -r vendor/${COMPANY}/libs/${BASE_PROJECT} vendor/${COMPANY}/libs/${NEW_PROJECT}
	elif [ "${action}" == "rename" ];then
		mv device/${COMPANY}/${BASE_PROJECT} device/${COMPANY}/${NEW_PROJECT}
		mv device/${COMPANY}/${NEW_PROJECT}/full_${BASE_PROJECT}.mk device/${COMPANY}/${NEW_PROJECT}/full_${NEW_PROJECT}.mk
		mv  vendor/mediatek/proprietary/custom/${BASE_PROJECT} vendor/mediatek/proprietary/custom/${NEW_PROJECT}
		mv vendor/mediatek/proprietary/trustzone/custom/build/project/${BASE_PROJECT}.mk vendor/mediatek/proprietary/trustzone/custom/build/project/${NEW_PROJECT}.mk
		mv vendor/${COMPANY}/libs/${BASE_PROJECT} vendor/${COMPANY}/libs/${NEW_PROJECT}
	fi
	sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g device/${COMPANY}/${NEW_PROJECT}/AndroidProducts.mk
	sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g device/${COMPANY}/${NEW_PROJECT}/BoardConfig.mk
	sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g device/${COMPANY}/${NEW_PROJECT}/device.mk
	sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g device/${COMPANY}/${NEW_PROJECT}/full_${NEW_PROJECT}.mk
	sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g device/${COMPANY}/${NEW_PROJECT}/vendorsetup.sh
	sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g device/${COMPANY}/${NEW_PROJECT}/kernel-autoconfig/debug_defconfig
	sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g device/${COMPANY}/${NEW_PROJECT}/kernel-autoconfig/user_defconfig
	sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g vendor/mediatek/proprietary/custom/${NEW_PROJECT}/security/efuse/input.xml
	sed -i s/${BASE_PROJECT}/${NEW_PROJECT}/g vendor/mediatek/proprietary/custom/${NEW_PROJECT}/Android.mk

	good "${action} android\t\tDone"
}

#拷贝到新文件夹
cpFile2New(){
	cd ${BASE_PROJECT}
	test -d ../${NEW_PROJECT} || mkdir -p ../${NEW_PROJECT}
	for p in $(git st -s . | grep '??'| sed 's#?? ##g') 
	do
		cp -rf --parents $p ../${NEW_PROJECT}/
	done 

	git clean -fd >/dev/null

	cd - >/dev/null
}
refreshFile(){
	cd ${NEW_PROJECT}
	find . -type f | sort | xargs -I {}  echo "AA {}" > file
	sed -i '/AA .\/file/d' file
	cd - > /dev/null

}
extraCopyfile(){
	warn $(pwd)
	cd ${BASE_PROJECT}
	#拷贝电池曲线文件(电池曲线属于modify状态,需要额外处理)
	#cp -rf --parents kernel-3.18/drivers/misc/mediatek/include/mt-plat/${PLATFORM}/include/mach/ ../${NEW_PROJECT}/
	cd - >/dev/null
}
deleteOverlay(){
	#删除代码内引用overlay
	#grep  -r "device/${COMPANY}/.*/overlay" ${NEW_PROJECT} | awk -F":" '{print$1}' | xargs sed -i  "/device\/${COMPANY}\/.*\/overlay/d" 2>/dev/null
	#删除overlay文件夹
	test -d ${NEW_PROJECT}/device/${COMPANY}/${NEW_PROJECT}/overlay && rm -rf ${NEW_PROJECT}/device/${COMPANY}/${NEW_PROJECT}/overlay/*
	echo -e "warning:\n\toverlay将不会再使用!!!" > ${NEW_PROJECT}/device/${COMPANY}/${NEW_PROJECT}/overlay/readme.txt
}

deleteCustom(){
	test -d ${NEW_PROJECT}/device/${COMPANY}/${NEW_PROJECT}/custom && rm -rf ${NEW_PROJECT}/device/${COMPANY}/${NEW_PROJECT}/custom
	

}

genReadme(){
	local action=$1
	local gitinfo=""
	if [ -f "./tools/gitinfo.sh" ];then
		gitinfo="./tools/gitinfo.sh"
	elif [ -f "../alps/teksun/tools/gitinfo.sh" ];then
		gitinfo="../alps/teksun/tools/gitinfo.sh"
	else
		warn "gitinfo.sh不存在"
	fi
	good "${gitinfo}:准备生成README.txt"
	echo "clone ${action} from ${BASE_PROJECT}" > "${NEW_PROJECT}/device/${COMPANY}/${NEW_PROJECT}/README.txt"
	${gitinfo} alps >> "${NEW_PROJECT}/device/${COMPANY}/${NEW_PROJECT}/README.txt"
	${gitinfo} teksun >> "${NEW_PROJECT}/device/${COMPANY}/${NEW_PROJECT}/README.txt"
}

commitProject(){
	git add ${NEW_PROJECT}
	git commit -m "gerrit:${NEW_PROJECT}:新建工程,克隆于${BASE_PROJECT}"

}

cloneall(){
	pushd $(pwd) >/dev/null
	cp -rf ${BASE_PROJECT} ${NEW_PROJECT}
	cd ${NEW_PROJECT}
	find . -type f | xargs sed -i "s/${BASE_PROJECT}/${NEW_PROJECT}/g"
	find . -name "${BASE_PROJECT}" -type d | sort -r | xargs rename "s/${BASE_PROJECT}/${NEW_PROJECT}/"
	for file in $(find . -name "*${BASE_PROJECT}*" -type f | sort -r )
	do
		cd $(dirname $file)
		rename "s/${BASE_PROJECT}/${NEW_PROJECT}/" $(basename $file)
		cd - > /dev/null
	done
	
	popd >/dev/null
	genReadme ${action}
	commitProject >/dev/null
	warn $(git log -1 --oneline)
	warn "${NEW_PROJECT}新建工程,提交成功"

}
#主函数
main(){
	pushd $(pwd) >/dev/null
	cd ${BASE_PROJECT}
	clonePreloader
	cloneLk
	cloneKernel
	cloneAndroid
	popd >/dev/null
	if [ "${action}" == "clone" ];then
		cpFile2New
		#可能需要的额外拷贝函数或者预处理
		extraCopyfile
	elif [ "${action}" == "rename" ];then
		mv ${BASE_PROJECT} ${NEW_PROJECT}
	fi
	#删除overlay
	deleteOverlay
	#删除custom文件夹
	#deleteCustom
	#生成readme文件
	genReadme ${action}
	#重新生成file文件列表
	refreshFile
	#做第一次提交
	if [ "${action}" == "clone" ];then
		commitProject >/dev/null
		#warn $(git log -1 --oneline)
		warn "${NEW_PROJECT}新建工程,提交成功"
	fi
}


#=================主函数入口====================#
if [ $# -lt 3 ]&&[ -z $(echo $1 | grep -oE "\-\-|\-") ];then 
	printHelp
fi
checkExecPath
forceUpdate
ROOTDIR=$(pwd)
ACTION=$1
shift
BASE_PROJECT=$1
NEW_PROJECT=$2
PLATFORM=$3
COMPANY=$4
#后续改为自动去代码里面获取这些信息,方便多平台移植
test -d "${BASE_PROJECT}" || die "目标拷贝工程不存在!"

if [ "$(getConfigValue MTK_K64_SUPPORT)" != yes ];then
	ARM_TYPE=arm
else
	ARM_TYPE=arm64
fi
test -z "${COMPANY}" && COMPANY=$(find ${BASE_PROJECT}/device/ -maxdepth 3 -name ProjectConfig.mk |  sed "s#.*device/\(.*\)/${BASE_PROJECT}.*#\1#g")
test -z "${PLATFORM}" && PLATFORM=$(getConfigValue MTK_PLATFORM | tr [A-Z] [a-z])
test -z "${KERNEL}" && KERNEL=$(find ${BASE_PROJECT} -maxdepth 1 -name kernel-* |xargs basename)

test -z "${PLATFORM}" && PLATFORM=mt6755
test -z "${COMPANY}" && COMPANY=teksun
test -z "${ARM_TYPE}" && COMPANY=arm
test -z "${KERNEL}" && KERNEL="kernel-3.18"

#===============腾瑞丰针对新项目名的限制要求===============#

#项目名称要小写,且符合项目部新项目要求
NEW_PROJECT=$(echo ${NEW_PROJECT} | tr [A-Z] [a-z] | grep -E "^[a-z][0-9]{3}[a-z0-9]{1,2}_v[0-9]{1,2}_[a-z0-9]{1,2}_.*|factory")

#新项目名要求不能超过32字符
if [ "${#NEW_PROJECT}" -gt "32" ];then
	die "error:$NEW_PROJECT工程名长度请不要超过32个字符，否则可能出现一些奇怪的问题"
fi

if [ -z "${NEW_PROJECT}" ];then
	die "error:工程名格式错误!"
fi

#=====================执行动作判断============================#

if [ "${ACTION}" == "--clone" -o  "${ACTION}" == "-clone" ];then
	action="clone"
elif [ "${ACTION}" == "--rename" -o "${ACTION}" == "-rename"  ];then
	action="rename"
elif [ "${ACTION}" == "--cloneall" -o "${ACTION}" == "-cloneall" ];then
	action="cloneall"
else
	printHelp
fi

#=====================标准参数打印================================#

warn "基础项目:${BASE_PROJECT}"
warn "目标项目:${NEW_PROJECT}"
warn "平台版本:${PLATFORM}"
warn "公司名称:${COMPANY}"
warn "芯片类型:${ARM_TYPE}"
warn "动作:${action}"

#===============主函数入口=================================#
if [ "${action}" == "cloneall" ];then
	cloneall
	exit
fi
main 





#添加clone project的readme,内容clone from和git info信息
#build/tools/gitinfo.sh
#########################################################################


#修改完后马上做一次提交
#########################################################################
